package com.inight.ojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.inight.ojcodesandbox.model.ExecuteCodeRequest;
import com.inight.ojcodesandbox.model.ExecuteCodeResponse;
import com.inight.ojcodesandbox.model.ExecuteMessage;
import com.inight.ojcodesandbox.model.JudgeInfo;
import com.inight.ojcodesandbox.utils.ProcessUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * java 原生的实现方式
 */
public class JavaNativeCodeSandboxOld implements CodeSandbox {


    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    private static final long TIME_OUT = 5000L;

    // 代码中有这些黑名单中的词 直接禁掉
    private static final List<String> blackList = Arrays.asList("Files", "exec");

    private static final WordTree WORD_TREE;
    private static final String SECURITY_MANAGER_CLASS_NAME = "MySecurityManager";
    // 到 path 中的上级目录, 不包括 class 本身
    private static final String SECURITY_MANAGER_PATH = "D:\\Java\\own\\inight-oj\\oj-code-sandbox\\src\\main\\resources\\security";

    static {
        WORD_TREE = new WordTree();
        WORD_TREE.addWords(blackList);
    }

    public static void main(String[] args) {
        JavaNativeCodeSandboxOld javaNativeCodeSandbox = new JavaNativeCodeSandboxOld();
        ExecuteCodeRequest request = new ExecuteCodeRequest();
        request.setInputList(Arrays.asList("1 2", "1 3"));
        // 从文件中读取内容
        String code = ResourceUtil.readUtf8Str("tmpCode/testCode/simpleComputeArgs/Main.java");
        request.setCode(code);
        request.setLanguage("java");
        ExecuteCodeResponse response = javaNativeCodeSandbox.executeCode(request);
        System.out.println(response);
    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {

        // 设置自己写的安全管理器. 这个应该设置到 命令行中
        // System.setSecurityManager(new DefaultSecurityManager());

        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        // 保存为文件之前, 先校验用户代码有没有危险代码, 比如操作文件和读文件
        // 利用 hutool 的字典树
//        WordTree wordTree = new WordTree();
//        wordTree.addWords(blackList);
        FoundWord foundWord = WORD_TREE.matchWord(code);
        if(foundWord != null) {
            // 说明有危险代码
            System.out.println("危险代码: " + foundWord.getFoundWord());
            return null;
        }

        // 1. 将用户提交的代码保存为文件
        // 获取用户工作文件路径
        String userDir = System.getProperty("user.dir");
        // D:\Java\own\inight-oj\oj-code-sandbox
        System.out.println("user.dir = " + userDir);
        //  File.separator 区分不太系统的分隔符：\\ or /
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        System.out.println(globalCodePathName);
        // 判断全局路径是否存在, 用到 hutool文件工具类, 比java 原生的读取文件 api要好用
        if(!FileUtil.exist(globalCodePathName)) {
            // 不存在, 就创建目录
            File mkdir = FileUtil.mkdir(globalCodePathName);
            // 创建之后的目录: D:\Java\own\inight-oj\oj-code-sandbox\tmpCode
            System.out.println("创建之后的目录: " + mkdir.getPath());
            // java 原生创建文件方式
//            File file = new File(globalCodePathName);
//            file.mkdir();
        }

        // todo 需要重新写一遍
        // 存在，则保存用户提交代码
        // 把用户的代码隔离存放，这个是目录
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        // 实际存放文件的目录
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME  ;
        // 写入文件. 利用 hutool 工具类
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        // 2、编译代码，得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            // 得到一个进程 Process
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            // 等待 Process 程序执行完，获取错误码
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(executeMessage);
        } catch (IOException e) {
            return getErrorResponse(e);
            // throw new RuntimeException(e);
        }

        // 3. 执行代码, 获取结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            // String runCmd = String.format("java -Xmx128m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
            String runCmd = String.format("java -Dfile.encoding=UTF-8 -cp %s;%s -Djava.security.manager=%s Main %s", userCodeParentPath,
                    SECURITY_MANAGER_PATH, SECURITY_MANAGER_CLASS_NAME, inputArgs);

            try {
                Process process = Runtime.getRuntime().exec(runCmd);
                // todo 新加, 判断是不是执行完了
                new Thread(() -> {
                    try {
                        // 先睡一个超时时间, 若是已经执行完, 摧毁也没事. 要是还没执行完, 直接销毁即可.
                        Thread.sleep(TIME_OUT);
                        System.out.println("代码超时, 已经中断");
                        process.destroy();

                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                });


                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(process, "运行");
                System.out.println(executeMessage);
                executeMessageList.add(executeMessage);
            } catch (IOException e) {
                return getErrorResponse(e);
                // throw new RuntimeException(e);
            }
        }

        // 4. 整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        // 执行错误
        List<String> outputList = new ArrayList<>();
        // 取用时最大值，便于判断是否超时
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                // 执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long executeTime = executeMessage.getTime();
            if (executeTime != null) {
                maxTime = Math.max(maxTime, executeTime);
            }
        }
        // 正常执行完成
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        // todo java 原生 通过 Process 获取到占用内存很麻烦,需要借助第三方库, 就不实现了, 用别的方式来实现.
        // judgeInfo.setMemory();
        judgeInfo.setTime(maxTime);
        executeCodeResponse.setJudgeInfo(judgeInfo);

        // 5. 清理文件
//        if(userCodeFile.getParentFile() != null) {
//            // userCodeFile.getParent();  这个是获取路径
//            // 先判断不为空再删除, 万一没有文件, 就会出现问题
//            boolean del = FileUtil.del(userCodeParentPath);
//            System.out.println("删除文件" + (del ? "成功" : "失败"));
//        }


        return executeCodeResponse;


    }

    /**
     * 错误信息处理, 提升程序健全性
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Exception e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        //  2 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        
        return executeCodeResponse;
    }
    
    
//    public static void main(String[] args) {
//        String property = System.getProperty("user.dir");
//        System.out.println(property);
//    }

}
